package com.futvan.z.erp.customer_notice;

import com.futvan.z.erp.customer.CustomerService;
import com.futvan.z.erp.customer.crm_customer;
import com.futvan.z.erp.customer_notice_send_message.Customer_notice_send_messageService;
import com.futvan.z.erp.customer_notice_sends.Customer_notice_sendsService;
import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.DateUtil;
import com.futvan.z.framework.util.EasemobUtil;
import com.futvan.z.framework.util.SmsUtil;
import org.springframework.stereotype.Service;
import com.futvan.z.framework.core.SuperService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class Customer_noticeService extends SuperService {

    @Resource
    CustomerService customerService;
    @Resource
    Customer_notice_sendsService notice_sendsService;
    @Resource
    Customer_notice_send_messageService messageService;

    /**
     * 发送通知
     *
     * @param customerList
     * @param type
     * @param title
     * @param content
     * @return
     * @throws Exception
     */
    public Result send(List<String> customerList, String type, String title, String content, String url) throws Exception {
        if (z.isNotNull(customerList)) {
            if (z.isNotNull(type)) {
                if (z.isNotNull(title)) {
                    if (z.isNotNull(content)) {
                        //检查用户有效性
                        List<crm_customer> effective = new ArrayList<>(); //有效集合
                        List<String> LoseEfficacy = new ArrayList<>(); //失效集合
                        //查询用户是否存在
                        for (int i = 0; i < customerList.size(); i++) {
                            //判断是否为手机号
                            if (isChinaPhoneLegal(customerList.get(i))) { //是手机号
                                List<crm_customer> infoList = customerService.getCustomerInfoByTel(customerList.get(i));
                                if (z.isNotNull(infoList) && infoList.size() > 0) {
                                    effective.add(infoList.get(0));
                                } else {
                                    LoseEfficacy.add(customerList.get(i));
                                }
                            } else {//不是手机号
                                crm_customer customerInfo = customerService.getCustomerInfo(customerList.get(i));
                                if (z.isNotNull(customerInfo)) {
                                    effective.add(customerInfo);
                                } else {
                                    LoseEfficacy.add(customerList.get(i));
                                }
                            }
                        }

                        //创建一个id
                        String zid = z.newNumber();
                        //将通知插入数据库
                        for (int i = 0; i < effective.size(); i++) {
                            CreateCustomerNotice(effective.get(i).getZid(), type, title, content, zid);
                        }
                        //创建通知记录
                        notice_sendsService.insertRecorde(zid, url, type, title, content, String.valueOf(effective.size()));

                        if (LoseEfficacy.size() > 0) {
                            return Result.error("成功发放" + effective.size() + "条数据\n" +
                                    "未查询到信息" + LoseEfficacy.size() + "条\n" +
                                    "分别为:" + LoseEfficacy);
                        }
                    } else {
                        return Result.error("内容不能为空");
                    }
                } else {
                    return Result.error("标题不能为空");
                }
            } else {
                return Result.error("发送类型不能为空");
            }
        } else {
            return Result.error("接收人列表不能为空");
        }
        return Result.success();
    }


    /**
     * 发送短信通知
     *
     * @param customerList
     * @param templateCode
     * @param url
     * @return
     * @throws Exception
     */
    public Result sendMessage(List<String> customerList, String templateCode, String url) throws Exception {
        if (z.isNotNull(customerList)) {
            if (z.isNotNull(templateCode)) {
                //检查用户有效性
                List<crm_customer> effective = new ArrayList<>(); //有效集合
                List<String> LoseEfficacy = new ArrayList<>(); //失效集合
                //查询用户是否存在
                for (int i = 0; i < customerList.size(); i++) {
                    //判断是否为手机号
                    if (isChinaPhoneLegal(customerList.get(i))) { //是手机号
                        List<crm_customer> infoList = customerService.getCustomerInfoByTel(customerList.get(i));
                        if (z.isNotNull(infoList) && infoList.size() > 0) {
                            effective.add(infoList.get(0));
                        } else {
                            LoseEfficacy.add(customerList.get(i));
                        }
                    } else {//不是手机号
                        crm_customer customerInfo = customerService.getCustomerInfo(customerList.get(i));
                        if (z.isNotNull(customerInfo)) {
                            effective.add(customerInfo);
                        } else {
                            LoseEfficacy.add(customerList.get(i));
                        }
                    }
                }

                if (effective.size() > 0) {
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < effective.size(); i++) {
                        sb.append(effective.get(i).getTel());
                        sb.append(",");
                    }
                    String tels = sb.deleteCharAt(sb.length() - 1).toString();//去掉最后一个逗号
                    Result result = SmsUtil.SendForTemplate(templateCode, tels);
                    if (result.ifSuccess()) {
                        //创建通知记录
                        messageService.insertRecordes(url, templateCode, String.valueOf(effective.size()));
                        //如果有无效用户则返回无效数据
                        String msg = "";
                        if (LoseEfficacy.size() > 0) {
                            msg = "成功发放" + effective.size() + "条信息" + "\n未成功发放" + LoseEfficacy.size() + "条,分别是：\n" + LoseEfficacy;
                        } else {
                            msg = "成功发放" + effective.size() + "条信息";
                        }

                        return Result.error(msg);
                    } else {
                        return Result.error(result.getMsg());
                    }
                } else {
                    return Result.error("没有有效用户");
                }

            } else {
                return Result.error("模版号不能为空");
            }
        } else {
            return Result.error("接收人列表不能为空");
        }
    }


    /**
     * 创建通知插入到数据库
     *
     * @param customerid
     * @param title
     * @param info
     */
    private void CreateCustomerNotice(String customerid, String notice_type, String title, String info, String notice_send_id) {
        crm_customer_notice c = new crm_customer_notice();
        String zid = z.newZid() + customerid;
        c.setZid(zid);
        c.setNumber(zid);
        c.setCreate_time(DateUtil.getDateTime());
        c.setCustomid(customerid);
        c.setNotice_type(notice_type);
        c.setIs_read("0");
        c.setTitle(title);
        c.setInfo(info);
        c.setNotice_send_id(notice_send_id);
        sqlSession.insert("crm_customer_notice_insert", c);
    }
    
    /**
     * 创建通知插入到数据库
     *
     * @param customerid
     * @param title
     * @param info
     */
    public Result CreateCustomerNoticeFromTicket(String customerid, String title, String info,String isTips) {
        Result result = new Result();

        crm_customer_notice c = new crm_customer_notice();
        String zid = z.newZid() + customerid;
        c.setZid(zid);
        c.setNumber(zid);
        c.setCreate_time(DateUtil.getDateTime());
        c.setCustomid(customerid);
        c.setNotice_type("1");
        c.setIs_read("0");
        c.setTitle(title);
        c.setInfo(info);
//        c.setNotice_send_id(z.newNumber());
        c.setIs_tips(isTips);

        int insert = sqlSession.insert("crm_customer_notice_insert", c);
        if(insert == 1){
            result.setSuccess();
        }else{
            result.setError("通知生成失败");
        }
         return result;
    }


    /**
     * 验证是否是手机号
     *
     * @param str
     * @return
     * @throws Exception
     */
    public static boolean isChinaPhoneLegal(String str) throws Exception {
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }
}
